import { store } from "../index";
import { defineStore } from "pinia";
import storage from "@/utils/storage";
import type { userInfoFace, userLoginType } from "@/types/user";
interface userState {
  token: undefined | string;
  userInfo: userInfoFace | undefined;
  loginDialog?: boolean;
  code: string;
}
import { info, wxLogin } from "@/api/user/login";
export const useUserStore = defineStore("user", {
  state: (): userState => {
    return {
      token: storage.get("token", false) as undefined | string,
      userInfo: storage.get("user", true) as undefined | userInfoFace, // 如果采用判断userInfoFace是否存在来进行路由监听就不要缓存 user了
      loginDialog: false,
      code: "",
    };
  },
  getters: {
    // 获取token
    getToken(): undefined | string {
      return this.token;
    },
    getUser(): userInfoFace | undefined {
      return this.userInfo;
    },
    getDialog(): boolean | undefined {
      return this.loginDialog;
    },
    getCode(): string {
      return this.code;
    },
  },
  actions: {
    setToken(token: string | undefined) {
      storage.set("token", token);
      this.token = token;
    },
    setUser(user: userInfoFace | undefined) {
      storage.set("user", user);
      this.userInfo = user;
    },
    setLoginDialog(status: boolean) {
      console.log("没登录");
      this.loginDialog = status;
    },
    /**
     * 获取code
     * @param islogin 是否强制重新获取
     * @returns Promise<string>
     */
    getLoginCode(islogin: boolean = false) {
      const that = this;
      return new Promise((resolve, reject) => {
        if (!this.getToken || islogin || !this.code) {
          this.loginCode()
            .then((code) => {
              return code;
            })
            .catch(() => {
              reject();
            });
        } else {
          wx.checkSession({
            success() {
              resolve(that.code);
            },
            fail() {
              that
                .loginCode()
                .then((code) => {
                  resolve(code);
                })
                .catch(() => {
                  reject();
                });
            },
          });
          resolve(this.code);
        }
      });
    },
    loginCode() {
      return new Promise((resolve, reject) => {
        uni.login({
          success: (res) => {
            this.code = res.code;
            resolve(res.code);
          },
        });
      });
    },
    // 静默登录
    silentLogin() {
      return new Promise((resolve, reject) => {
        this.loginCode().then((code) => {
          wxLogin({ code }).then((res) => {
            this.setToken(res.data.token);
            this.getuserInfo().then(() => {
              resolve("");
            });
          });
        });
      });
    },
    getuserInfo(): Promise<userInfoFace> {
      return new Promise((resolve, reject) => {
        // 登录
        info()
          .then((res) => {
            this.setUser(res.data);
            resolve(res.data);
          })
          .catch((err) => {
            console.log(err);
            reject(err);
          });
      });
    },
    loginOut() {
      this.setToken(undefined);
      this.setUser(undefined);
    },
  },
});
// 如果需要初始化时执行，则可以采用此方法
export const useUserStoreWithOut = () => {
  return useUserStore(store);
};
